;(function ($) {
    $.widget("tempo.fileupload", {
        options: {
            name: null,
            accept: "*",
            btnText: null,
            change: $.noop,
            fileName: null,
            fileId: null,
            flowid: null,
            fileNameWidth: 240,
            themeid: null,
            enable: true,
            initModelBtn: false,
            modelFileName: "",
            async: true
        },
        _getAdaptingName: function (fileName, currWidth, resultName) {
            var trueEle = $('<pre>' + fileName + '</pre>').css({
                'display': 'none',
                'font-family': 'Microsoft yahei',
                'font-size': '1em'
            }).appendTo($("body"));
            var trueWidth = trueEle.width();
            if (currWidth <= trueWidth) {
                var newFileName = fileName.substring(0, fileName.length - 3);
                trueEle.text(newFileName);
                resultName = trueEle.text() + "...";
                trueEle.remove();
                return this._getAdaptingName(trueEle.text(), currWidth, resultName);
            } else {
                trueEle.remove();
                if (resultName !== 0) {
                    return resultName;
                } else {
                    return fileName;
                }
            }
        },
        _create: function () {
            if (!this.element.is("div")) {
                $.error("上传组件必须为div元素");
                return;
            }
            this.options.themeid = this.options.themeid || window.analyse_id;
            this.options.flowid = this.options.flowid || (window.analyseStatus && window.analyseStatus.getMainId());
            if (!this.options.themeid) {
                $.error("主题id不能为空");
                return;
            }
            if (!this.options.flowid && window.apiDesigner && window.apiDesigner == true) {
                this.options.flowid = window.flowid;
            }
            if (!this.options.flowid) {
                $.error("流程id不能为空");
                return;
            }
            this.element.addClass('tempo-fileupload');
            var form = $('<form>').appendTo(this.element).attr('enctype', 'multipart/form-data').attr('method', 'post');
            form.attr("action", contextPath + '/api/ai/mineresource/save');
            $('<input name="themeid" class="themeid" type="hidden">').appendTo(form).val(this.options.themeid);
            $('<input name="flowid" class="flowid" type="hidden">').appendTo(form).val(this.options.flowid);
            $('<input name="fileId" class="fileId" type="hidden">').appendTo(form).val(this.options.fileId);
            var omitEle = $('<pre>...</pre>').css({
                'display': 'none',
                'font-family': 'Microsoft yahei',
                'font-size': '1em'
            }).appendTo($("body"));
            var newFileName = this._getAdaptingName(this.options.fileName, this.options.fileNameWidth - 8 - omitEle.width(), 0);
            omitEle.remove();
            var filenameText = $('<input class="nameshow">').appendTo(form).validatebox({
                readonly: true,
                width: this.options.fileNameWidth
            }).val(newFileName).attr("title", this.options.fileName).attr("id", this.options.fileName);
            var wrapper = $('<a href="javascript:void(0)" class="file">').appendTo(form).text(this.options.btnText || TempoUtils.locale("mine.flow_choose")).attr('title', '请选择上传文件');
            this.options.wrapper = wrapper;
            var fileInput = $('<input class="uploadinput">').attr('type', 'file').attr('name', 'file').attr('accept', this.options.accept).appendTo(wrapper);
            var $this = this;
            if (this.options.fileId) {
                var downLoadBtn = $('<button class="tempo-button" style="margin-left:10px;" type="button">' + TempoUtils.locale("mine.xiazai") + '</button>').appendTo(form);
                downLoadBtn.button();
                downLoadBtn.unbind('click').bind('click', function () {
                    $this._downLoadCustomFile();
                });
            }
            if (this.options.initModelBtn) {
                var modelBtn = $('<button style="margin-left:10px;">' + TempoUtils.locale("mine.down_model_file") + '</button>').appendTo(form);
                /**
                 * 初始化模板下载按钮
                 */
                modelBtn.button({
                    'click': function (e) {
                        e.preventDefault();
                        var url = contextPath + '/api/ai/textmining/downloadModel';
                        var modelData = {
                            "fileName": $this.options.modelFileName,
                            "time": (new Date()).getTime()
                        };
                        TempoUtils.downLoadFile({
                            url: url,
                            data: modelData
                        });
                        return false;
                    }
                });
            }
            this.fileInput = fileInput;
            this.setEnable(this.options.enable);
        },

        _downLoadCustomFile: function () {
            var $this = this;
            if ($this.options.fileId && $this.options.fileId.length > 0) {
                TempoUtils.downLoadFile({
                    url: contextPath + '/api/ai/mineresource/downloadResourceFile',
                    data: {
                        fileId: $this.options.fileId,
                        fileName: $this.options.fileName
                    }
                });
            }
        },

        save: function (callback) {
            var that = this;
            var form = that.element.find('form');
            if (that._hasChanged && that.options.enable) {
                form.ajaxSubmit({
                    dataType: 'json',
                    type: 'post',
                    async: that.options.async,
                    beforeSubmit: function (result) {
                        return true;
                    },
                    success: function (data) {
                        if (data.success) {
                            var record = {};
                            record.fileId = data.data;
                            var fileName = form.find('.nameshow').attr("id");
                            record.fileName = fileName;
                            that.element.find('input[name="fileId"]').val(record.fileId);
                            callback(record);
                        } else {
                            TempoUtils.uploadErrorHandler({});
                        }
                    },
                    error: function (e) {
                        TempoUtils.uploadErrorHandler(e);
                    }
                });
            } else {
                return this.getFileRecord();
            }
        },

        getFileRecord: function () {
            var record = {};
            var fileName = this.element.find('.nameshow').attr("id");
            record.fileName = fileName;
            record.fileId = this.element.find('input[name="fileId"]').val();
            return record;
        },

        setEnable: function (enable) {
            this.options.enable = enable;
            var wrapper = this.element.find('.file');
            wrapper.addClass('disabled')
            if (enable) {
                this.fileInput.removeAttr('disabled');
                wrapper.removeClass('disabled')
            } else {
                this.fileInput.attr('disabled', 'disabled');
            }
            this._registerEvent();
        },


        _registerEvent: function () {
            var that = this;
            if (this.options.enable) {
                that.fileInput.unbind('change').bind("change", function (e) {
                    var files = e.currentTarget.files;
                    var fileName = files[0].name;
                    var curFileSuffix = fileName.substr(fileName.lastIndexOf(".")).toLowerCase();
                    var acceptType = that.options.accept;
                    var wrapper = that.options.wrapper;
                    if ('*' != acceptType) {
                        var acceptTypeArr = acceptType.split(",");
                        if (acceptTypeArr.indexOf(curFileSuffix) == -1) {
                            $("<div/>").alert({
                                msg: "只支持" + acceptType + "格式的文件！",
                                title: TempoUtils.locale("mine.prompt")
                            });
                            var wrapper = that.options.wrapper;
                            wrapper.attr('title', '请选择上传文件');
                            return;
                        }
                    }
                    if (files[0].size == 0) {
                        $("<div/>").alert({
                            msg: "文件内容为空，请重新上传！",
                            title: TempoUtils.locale("mine.prompt")
                        });
                        return;
                    }
                    var file = that._getFile();
                    that._hasChanged = true;
                    if (file) {
                        var omitEle = $('<pre>...</pre>').css({
                            'display': 'none',
                            'font-family': 'Microsoft yahei',
                            'font-size': '1em'
                        }).appendTo($("body"));
                        var newFileName = that._getAdaptingName(file.name, that.options.fileNameWidth - 8 - omitEle.width(), 0);
                        omitEle.remove();
                        that.element.find('.nameshow').val(newFileName).attr('title', file.name).attr("id", file.name);
                        that.options.change.apply(that, {file: file});
                        wrapper.attr('title', file.name);
                    }
                });
                this.element.find('.file').unbind('click').bind('click', function (event) {
                });
            } else {
                this.element.find('.file').unbind('click').bind('click', function (event) {
                    event.preventDefault();
                });
            }
        },

        //获取选择的文件
        _getFile: function () {
            if (!this.options.accept) {
                return this.fileInput[0].value;
            }

            var files = this.fileInput[0].files;
            var accepts = this.options.accept.split(",").map(function (item) {
                return item.trim();
            });
            var msg = null, result = null;
            if (files && files.length != 0) {
                if (files[0].type) {
                    if ($.inArray(files[0].type, accepts) < 0) {
                        msg = this.options.errormsg;
                    }
                } else {
                    var name = files[0].name;
                    name = name.substring(name.lastIndexOf("."), name.length);
                    if ($.inArray(name, accepts) < 0) {
                        msg = this.options.errormsg;
                    }
                }
                result = files[0];
            } else {
                var val = this.fileInput[0].value,
                    name = val.substring(val.lastIndexOf(".") + 1, val.length);
                accepts = accepts.map(function (item) {
                    var items = item.split("/");
                    item = items.slice(-1)[0];
                    if (item.indexOf(".") != -1) {
                        item = item.substring(item.indexOf(".") + 1);
                    }
                    return item;
                })
                if (name && $.inArray(name, accepts) < 0) {
                    msg = this.options.errormsg;
                } else {
                    result = val;
                }
            }
            return result;
        },

        hasSelectedFile: function () {
            // 判断组件是否已经选择了文件
            var thisFileName = this.element.find(".nameshow");
            if (thisFileName && thisFileName.val() && thisFileName.val() != "") {
                return true;
            }
            return false;
        },
        /**
         * 判断当前上传的文件名是否存在，且为允许的类型，如，若只允许txt文件，则传入['txt']
         */
        validIsAcceptType: function (typeArray) {
            var thisFileName = this.element.find(".nameshow");
            if (!thisFileName || thisFileName.val() == "") {
                return false;
            }
            if (!typeArray || typeArray.length == 0) {
                return true;
            }
            for (var i = 0; i < typeArray.length; i++) {
                if (TempoMineUtils.endsWith(thisFileName.val(), typeArray[i])) {
                    return true;
                }
            }
            return false;
        }
    });
})(jQuery)
